<?php


namespace app\common\cachemodel;


use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\BaseCache;
use app\common\model\Goods;
use app\common\model\MessageCenter;
use app\common\model\UserPush;
use think\Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlVipBoon extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_vip_boon';

    protected $cacheModel = 'vip.vip_boon';

    private $couponTypeName = [
        1 => '折扣',
        2 => '立减',
        3 => '满减',
        4 => '随机',
        5 => '免费',
    ];

    /**
     * 会员VIP权益优惠券赠送
     * @param int $uid
     * @throws \Exception
     */
    public function vipBoonSend(int $uid): void
    {
        $userVipModel = new ZlUserVip();
        $userVip = $userVipModel->getInfoById($uid);
        if ($userVip && $userVip['is_valid'] == 1)
        {
            $userPush = (new UserPush())->getUserRegid($uid);
            if ($userPush && isset($userPush['version']) && $userPush['version'])
            {
                $userVersion = substr($userPush['version'], 1, strlen($userPush['version']));
                $isNewBoon = Util::CheckAppVersion('2.10.5', $userVersion) !== '小';
            } else
            {
                $isNewBoon = false;
            }
            $vipBoon = $this->getVipBoon($userVip['vip_level'], $isNewBoon);
            if ($vipBoon)
            {   // 用户权益赠送
                $ids = [];
                $giveIds = [];
                $time = time();
                $userCouponModel = new UserCoupon();
                $this->startTrans();
                try
                {
                    foreach ($vipBoon as $item)
                    {
                        for ($i = 0; $i < $item['num']; $i++)
                        {
                            $cData = [
                                'uid' => $uid,
                                'c_id' => $item['c_id'],
                                'ur_id' => $item['ur_id'],
                                'start_time' => $time,
                                'end_time' => strtotime("+{$item['duration']} day"),
                                'give_time' => $time,
                                'status' => 0,
                                'price' => $item['type'] == 4 ? mt_rand($item['rand_min'], $item['rand_max']) : 0,
                                'is_give' => $item['is_give'],
                                'create_time' => $time,
                                'update_time' => 0,
                            ];
                            $ucId = $userCouponModel->insertGetId($cData);
                            $ids[$ucId] = $ucId; // 添加未用于ID
                            if ($item['is_give'] == 1)
                            {
                                $giveIds[$ucId] = $ucId;
                            }

                            $gidsArr = explode(',', $item['gids']);

                            $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');

                            // 神策打点 75 获得优惠券 AcquireCoupon
                            SensorsData::track($uid, true, 'AcquireCoupon', [
                                'refer_name' => '',
                                'refer_link' => '',
                                'coupon_name' => $item['cname'],
                                'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                                'coupon_type' => $this->couponTypeName[$item['type']],
                                'coupon_range' => $couponRangeArr,
                                'acquire_channel' => '会员权益',
                                'is_give' => $cData['is_give'] ? true : false,
                                'acquire_scene' => '权益发放',
                            ]);
                        }
                    }

                    $userVipModel->where(['id' => $userVip['id']])->update(['send_time' => $time]);
                    $this->commit();
                }
                catch (Exception $e)
                {
                    Log::write('赠送会员权益失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error');
                    $this->rollback();
                    return;
                }

                if ($ids)
                {   // 未使用
                    $userCouponModel->listDataAdd($uid, $ids, 1);
                }
                if ($giveIds)
                {   // 可赠与
                    $userCouponModel->listDataAdd($uid, $giveIds, 2);
                }
                $vipBoonMessage = $this->getBoonMessageString($userVip['vip_level'], $vipBoon, 2, $isNewBoon);
                $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $uid]);
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $uid,
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 0,
                    'title' => '会员权益赠送提醒',
                    'content' => "尊贵的V{$userVip['vip_level']}会员：{$userInfo['nickname']}，您的本月会员权益：{$vipBoonMessage} 已放入您的【卡券中心】，快去使用吧~",
                    'link' => 'discount_coupon_center?need_auth=2',
                    'target' => 'local',
                    'create_time' => time(),
                ];
                //发送消息
                try
                {
                    (new MessageCenter())->pushMessage($uid, $messageData);
                }
                catch (Exception $e)
                {
                    print("会员 写入消息中心失败: " . $e->getMessage() . PHP_EOL);
                    Log::write("会员 写入消息中心失败: " . $e->getMessage() . PHP_EOL, 'error');
                }
            }
        }
    }

    /**
     * 获取相应等级的会员权益
     * @param int $level
     * @return array
     * @throws \Exception
     */
    public function getVipBoon(int $level, bool $isNewBoon = false)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $level)->getDataAndSet(function () use ($level)
        {
            return $this->getVipBoonInData($level);
        });

        $data = is_array($data) ? $data : json_decode($data, true);

        if ($isNewBoon)
        {   // 新版本 权益
            foreach ($data as $k => $item)
            {
                if (in_array((int)$item['c_id'], [7, 8, 11, 17], true))
                {
                    unset($data[$k]);
                }
            }
        }

        return $data;
    }

    /**
     * 通过数据库获取VIP等级权益信息
     * @param int $level
     * @return array
     */
    public function getVipBoonInData(int $level)
    {
        try
        {
            $data = $this->alias('b')
                ->join('wechat_backup_07_18_14_43_00.zl_coupon_attr c', 'b.c_id=c.id')
                ->where('b.vip_level', $level)->where('b.status', 1)
                ->column('b.vip_level,b.c_id,b.num,b.name,b.cycle,b.duration,b.is_give,c.ur_id,c.type,c.rand_min,c.rand_max,c.name cname,c.gids', 'b.id');
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取消息中心VIP权益消息 字符串格式
     * @param int $level VIP等级
     * @param array $boonInfo 权益信息
     * @param int $type 1升级消息 2赠送消息
     * @return string
     * @throws \Exception
     */
    public function getBoonMessageString(int $level, array $boonInfo = [], int $type = 1, bool $isNewBoon = false): string
    {
        if (empty($boonInfo))
        {
            $boonInfo = $this->getVipBoon($level, $isNewBoon);
        }

        $str = '';
        foreach ($boonInfo as $item)
        {
            if ($type === 1)
            {
                $str .= "{$item['name']} {$item['num']}张/月、 ";
            } else
            {
                $str .= "{$item['name']} x{$item['num']}；";
            }
        }

        $str = rtrim(trim($str), '、');

        return $str;
    }
}
